﻿<%@ WebHandler Language="C#" Class=" ValidateCode" %>

using System;
using System.Web;
using System.Web.SessionState;
using Hjp.FrameWork.Common;
using System.Drawing;

public class ValidateCode : IHttpHandler, IRequiresSessionState
{

    public void ProcessRequest(HttpContext context)
    {
        int length = Utils.StrToInt(context.Request["length"], 4);

        string checkCode = CreateRandomCode(length);
        CreateImage(checkCode, context);
    }

    public bool IsReusable
    {
        get { return true; }
    }

    private string CreateRandomCode(int codeCount)
    {
        string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,W,X,Y,Z";
        string[] allCharArray = allChar.Split(',');
        string randomCode = "";
        int temp = -1;

        Random rand = new Random();
        for (int i = 0; i < codeCount; i++)
        {
            if (temp != -1)
            {
                rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
            }
            int t = rand.Next(35);
            if (temp == t)
            {
                return CreateRandomCode(codeCount);
            }
            temp = t;
            randomCode += allCharArray[t];
        }
        return randomCode;
    }

    private void CreateImage(string checkCode, HttpContext context)
    {
        int iwidth = (int)(checkCode.Length * 12);
        System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 20);
        Graphics g = Graphics.FromImage(image);
        Font f = new System.Drawing.Font("Arial", 10, System.Drawing.FontStyle.Bold);
        Brush b = new System.Drawing.SolidBrush(Color.Red);
        //g.FillRectangle(new System.Drawing.SolidBrush(Color.Blue),0,0,image.Width, image.Height);
        g.Clear(Color.WhiteSmoke);
        g.DrawString(checkCode, f, b, 3, 3);

        //Random r = new Random();
        //Pen linePen = new Pen(new SolidBrush(Color.LightYellow), 2);
        //for (int x = 0; x < 6; x++)
        //    g.DrawLine(linePen, new Point(r.Next(0, 199), r.Next(0, 59)), new Point(r.Next(0, 199), r.Next(0, 59)));

        image.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
        //context.Response.ClearContent();
        context.Session["CheckCode"] = checkCode;
        context.Response.ContentType = "image/Jpeg";
        context.Response.End();
        g.Dispose();
        image.Dispose();

    }
}